package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.ExportProductService;
import cn.itcast.service.cargo.ExportService;
import cn.itcast.service.cargo.PackingService;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

@Controller
@RequestMapping("/cargo/packing")
public class PackingController extends BaseController {

    @Reference
    private ExportService exportService;

    @Reference
    private ExportProductService exportProductService;

    @Reference
    private PackingService packingService;

    /**
     * 1. 装箱管理列表
     */
    @RequestMapping("/list")
    public String contractList(@RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "5") Integer pageSize) {

        PackingExample packingExample = new PackingExample();
        packingExample.createCriteria().andCompanyIdEqualTo(getLoginCompanyId());
        packingExample.setOrderByClause("create_time desc");
        PageInfo<Packing> pageInfo = packingService.findByPage(packingExample, pageNum, pageSize);
        request.setAttribute("pageInfo",pageInfo);
        return "cargo/packing/packing-list";
    }

    /**
     * 3. 添加购销合同或修改购销合同
     */
    @RequestMapping("/edit")
    public String edit(Packing packing) {
        // 设置企业id、企业名称
        packing.setCompanyId(getLoginCompanyId());
        packing.setCompanyName(getLoginCompanyName());

        // 根据id判断是添加还是修改
        if (StringUtils.isEmpty(packing.getPackingListId())) {
            // 设置创建时间
            packing.setCreateTime(new Date());
            // 创建人
            packing.setCreateBy(getLoginUser().getId());
            // 创建人所属部门
            packing.setCreateDept(getLoginUser().getDeptId());
            // 添加
            packingService.save(packing);
        } else {
            // 修改
            packingService.update(packing);
        }
        return "redirect:/cargo/packing/list";
    }

    @RequestMapping("/delete")
    @ResponseBody
    public Map<String,Object> delete(String id){
        return packingService.delete(id);
    }

    /*/cargo/packingList/toPack.do*/
    @RequestMapping("/toPack")
    public String toPack(String id){
        Map<String, Object> map = new HashMap<>();
        String[] exportIds = id.split(",");
        // 1 如果为1 直接存储数据转入到前端
        if (exportIds.length == 1){

            Export export = exportService.findById(id);
            if (export.getShipmentPort() == null || export.getDestinationPort() == null || export.getConsignee() == null || export.getState() !=2){
                throw new RuntimeException("你选择的报运单不符合要求（装运港、目的港、收货人不一致（或为空）),或者选择了未报运成功的订单");
            }

            map = saveData(export);
            map.put("exportIds",id);
            map.put("exportNos",export.getCustomerContract());
        } else {
            //2 转换为 exportIdList 集合 去后端查询
            List<String> exportIdList = Arrays.asList(exportIds);
            ExportExample exportExample = new ExportExample();
            exportExample.createCriteria().andIdIn(exportIdList);
            List<Export> exportList = exportService.findByIds(exportExample);
            Export exportFirst = exportList.get(0);
            if (exportFirst.getShipmentPort()==null || exportFirst.getDestinationPort()==null || exportFirst.getConsignee()==null){
                throw new RuntimeException("你选择的报运单不符合要求（装运港、目的港、收货人不一致（或为空）),或者选择了未报运成功的订单");
            }
            for (int i = 1; i < exportList.size(); i++) {
                if (exportList.get(i).getShipmentPort()== null || !exportFirst.getShipmentPort().equals(exportList.get(i).getShipmentPort()) || exportList.get(i).getState() !=2){
                    throw new RuntimeException("你选择的报运单不符合要求（装运港、目的港、收货人不一致（或为空）),或者选择了未报运成功的订单");
                }
                if (exportList.get(i).getDestinationPort()== null || !exportFirst.getDestinationPort().equals(exportList.get(i).getDestinationPort())){
                    throw new RuntimeException("你选择的报运单不符合要求（装运港、目的港、收货人不一致（或为空）),或者选择了未报运成功的订单");
                }
                if (exportList.get(i).getConsignee()== null || !exportFirst.getConsignee().equals(exportList.get(i).getConsignee())){
                    throw new RuntimeException("你选择的报运单不符合要求（装运港、目的港、收货人不一致（或为空）),或者选择了未报运成功的订单");
                }
            }
            // 设置 合同版本号
            String exportNos = "";
            Double totalVolume = 0d;
            Double netWeights = 0d;
            Double grossWeights = 0d;
            Double packingMoney = 0d;
            for (Export export : exportList) {
                if (export.getCustomerContract()!=null){
                    exportNos += export.getCustomerContract();
                }
                // 1.2 通过商品计算出来的 数据
                map = saveData(export);
                totalVolume += (Double)map.get("totalVolume");
                netWeights += (Double)map.get("netWeights");
                grossWeights += (Double)map.get("grossWeights");
                packingMoney += (Double)map.get("packingMoney");
            }
            map.put("totalVolume",totalVolume);
            map.put("netWeights",netWeights);
            map.put("grossWeights",grossWeights);
            map.put("packingMoney",packingMoney);
            map.put("exportIds",id);
            map.put("exportNos",exportNos);
        }
        request.setAttribute("map",map);
        return "cargo/packing/packing-toPack";
    }

    public Map<String,Object> saveData(Export export){
        Map<String,Object> map = new HashMap<>();
        ExportProductExample exportProductExample = new ExportProductExample();
        exportProductExample.createCriteria().andExportIdEqualTo(export.getId());
        List<ExportProduct> exportProductList = exportProductService.findAll(exportProductExample);
        Double totalVolume = 0d;
        Double netWeights = 0d;
        Double grossWeights = 0d;

        if (exportProductList!=null && exportProductList.size() >0){
            for (ExportProduct exportProduct : exportProductList) {
                if (exportProduct.getSizeHeight()!=null && exportProduct.getSizeLength()!=null && exportProduct.getSizeWidth()!=null){
                    totalVolume += exportProduct.getSizeHeight()*exportProduct.getSizeLength()*exportProduct.getSizeWidth();
                }
                if (exportProduct.getNetWeight()!=null){
                    netWeights += exportProduct.getNetWeight();
                }
                if (exportProduct.getGrossWeight()!=null){
                    grossWeights += exportProduct.getGrossWeight();
                }
            }
        }
        Double packingMoney = grossWeights*520;
        map.put("totalVolume",totalVolume);
        map.put("netWeights",netWeights);
        map.put("grossWeights",grossWeights);
        map.put("packingMoney",packingMoney);
        return map;
    }
}
